import Taro from '@tarojs/taro'
import CryptoJS from 'crypto-js'
import { getSessionKey } from '@/api/user/index'
import { IS_USERINFO } from '@/store/user/action-types'

const getByteLen = (val: any) => {
  let len = 0
  if (!val) {
    len = 0
  } else {
    for (let i = 0; i < val.length; i++) {
      if (String(val[i]).match(/[^\x00-\xff]/gi) !== null) {
        len += 3
      } else {
        len += 1
      }
    }
  }
  return len.toString()
}

interface ObjValueType {
  method: string
  url: string
  data?: object | string
}

// 用户鉴权加密
export const genSignature = ({ method, url, data }: ObjValueType) => {
  const USERINFO = Taro.getStorageSync(IS_USERINFO)
  if (!USERINFO) return {}
  let { accessId, accessKey, serverTime } = USERINFO
  if (!accessId) return {}
  let clientTime = Date.parse(new Date()['toGMTString']()) / 1000
  let entityLength: string = '0'
  // 服务端时间的处理
  let serverTimeStamp = serverTime

  // 客户端时间的处理
  let clientTimeStamp = typeof clientTime === 'number' ? clientTime : 0
  if (!clientTimeStamp) {
    let date = new Date()['toGMTString']()
    clientTimeStamp = Date.parse(date) / 1000// 客户端时间戳
    clientTime = clientTimeStamp
  }

  // 时间差的处理
  let difTimestamp = Number(serverTimeStamp) - Number(clientTimeStamp)// 客户端时间与服务器时间差
  let clientCorrectTimeStamp = +new Date() / 1000 + difTimestamp// 当下正确时间戳
  clientTime = new Date(clientCorrectTimeStamp * 1000)['toGMTString']()// 当下正确时间

  if (/^P(OST|UT)$/.test(method)) {
    entityLength = getByteLen(data)
  }
  // 加密URL的处理
  if (url.indexOf('?') !== -1) {
    let endLength = url.indexOf('?')
    url = url.substr(0, endLength)
  }
  url = url.substr(1, url.length)
  let str = method + '\\n' + url + '\\n' + entityLength + '\\n' + clientTime
  let hash = CryptoJS.HmacSHA1(str, accessKey)
  let sha = hash.toString(CryptoJS.enc.Base64)
  let auth = 'Jekun ' + accessId + ':' + sha
  // console.log(`
  //     str:${str}
  //     hash:${hash}
  //     sha:${sha}
  //     auth:${auth}
  //     accessId: ${accessId}
  //     accessKey: ${accessKey}
  // `)
	console.log('auth----调试',auth)
  const AuthHeader = {
    // 'from': accessId,
    'Authorization': auth,
    'Entity-Date': clientTime,
    'Entity-Length': entityLength,
    'str': str,
    'accessKey': accessKey.substring(accessKey.length - 10)
  }
  return AuthHeader
}

// 检测sessionKey是否有效
export const checkSession = async () => {
  try {
    const result = await Taro.checkSession()
    // console.log('checkSession result', result)
    if (result.errMsg === 'checkSession:ok') {
      return true
    } else {
      return false
    }
  } catch (e) {
    return false
  }
}

// 获取sessionkey
export const isSessionKey = async () => {
  console.log('isSessionKey----------isSessionKey')
  const sessionKey = Taro.getStorageSync('IS_SESSIONKEY')
  if (sessionKey) {
    const checkSessionEffective = await checkSession()
    if (checkSessionEffective) {
      Taro.setStorageSync('IS_SESSIONKEY', sessionKey)
      return sessionKey
    } else {
      return login()
    }
  } else {
    return login()
  }
}

// 获取支付宝小程序AuthCode码
export const getAuthCode = async()=>{
	my.getAuthCode({
		scopes: ['auth_base'],
	 // 主动授权：auth_user，静默授权：auth_base或者其它scope。如需同时获取用户多项授权，可在 scopes 中传入多个 scope 值。
		success: (res) => {
			Taro.setStorageSync('AUTH_CODE', res.authCode)
		},
	})
}

// 重新获取sessionkey
export const getNewSessionKey = async () => {
  return login()
}

// 获取最新的 code
const login = async () => {
  try {
    const resulte = await Taro.login()
    const resInfo: any = await getSessionKey({
      code: resulte.code
    })
    if (resInfo.data.success) {
      const data = resInfo.data.data
      Taro.setStorageSync('IS_SESSIONKEY', data.sessionKey)
      Taro.setStorageSync('IS_OPENID', data.openId)
      return data.sessionKey
    }
  } catch (e) {
    console.log(e)
  }
}

// 获取用户授权
export const userInfoAuth = async () => {
  try {
    const result = await Taro.getSetting()
    const authStatus = result.authSetting['scope.userInfo']
    if (authStatus) {
      return true
    } else {
				await Taro.authorize({ scope: 'scope.userInfo' })
				return true
    }

  } catch (e) {
    console.log(e)
    return false
  }
}
